package com.it.gw.modules.station.activity

import EquimentKeyValueVo
import EquimentVo
import EquimentVoList
import LoginVo
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.it.common.bean.CommonBean
import com.it.common.utils.DisplayUtil
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.StringUtils
import com.it.common.utils.isNotEmpty
import com.it.data.manager.AppCacheManager
import com.it.data.network.req.DealOrderDetailDto
import com.it.data.network.req.ProblemDto
import com.it.data.network.req.ProblemUploadDto
import com.it.data.network.req.Product
import com.it.data.network.req.SaveQuePicDto
import com.it.data.network.req.UploadFileDto
import com.it.data.network.rsp.FileVo
import com.it.data.network.rsp.GQYWXXVo
import com.it.data.network.rsp.ProblemReportVo
import com.it.data.network.rsp.QuaTypeVo
import com.it.data.network.rsp.UnresolvedVo
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityGqstationReportBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.modules.station.adapter.ProblemReportDetailAdapter
import com.it.gw.modules.station.adapter.QuaTypeAdapter
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.io.File


//站点图片
class GQStationReportDetailActivity : BaseActivity<ActivityGqstationReportBinding>() {


    companion object {
        const val TAG = "OperationRecordActivity"
    }

    private val dataList by lazy { mutableListOf<QuaTypeVo>() }
    private val adapter by lazy {
        QuaTypeAdapter(context = this, datas = dataList, listener = {


        })
    }

    private fun refreshQuaTypeView() {
        adapter.notifyDataSetChanged()
    }

    private val problemDataList by lazy { mutableListOf<ProblemReportVo>() }
    private val problemReportAdapter by lazy {
        ProblemReportDetailAdapter(context = this, datas = problemDataList, listener = {

        }, type = intent.getIntExtra("type", 1))
    }


    /**
     * 选择问题类型
     * @param queType String
     * @param queTypeName String?
     */
    private fun selectProblem(queType: String, queTypeName: String?, unresolvedVo: UnresolvedVo) {
        ProgressDialog.show(this)
        //获取处理方式
        gqStationViewModel.getQuaTypeSell(sttp = gqywxxVo!!.sttp!!, queId = queType, resp = {
            ProgressDialog.hide()
            var checkedIdList =
                unresolvedVo.opQueDealDtoList?.filter { it.checked == "true" }?.map { it.dealcode }
                    ?.toMutableList()

            if (it.data.isNotEmpty() && checkedIdList.isNotEmpty()) {
//                val vo = it.data?.filter { it.id in  checkedIdList }
//                vo?.selected = true;
                it.data?.forEach { dd ->
                    if (dd.id in checkedIdList!!) {
                        dd.selected = true;
                    }
                }

            }
            Log.d(TAG, "selectProblem: ${checkedIdList}")
            Log.d(TAG, "selectProblem: ${it.data}")
            val problemReportVo = ProblemReportVo(
                id = queType,
                operationType = queTypeName,
                dealMethods = it.data,
                needAssist = unresolvedVo.needAssist,
                queDeal = unresolvedVo.queDeal,
                needAssistEnable = unresolvedVo.needAssist != "1",
                queDealEnable = unresolvedVo.queDeal != "1",
                problemDesc = unresolvedVo.queContent,
                dealDesc = unresolvedVo.processing,
            )
            unresolvedVo.opQueDealDtoList?.forEach { un ->
                runCatching {
                    var equimentVoList = mutableListOf<EquimentVo>()
                    equimentVoList.add(EquimentVo(equipment = un.linkField?.get(0)?.value))
                    equimentVoList.add(
                        EquimentVo(
                            id = un.dealcode,
                            cl_CODE = un.linkField?.get(1)?.key,
                            equipment = "${un.linkField?.get(1)?.value}"
                        )
                    )
                    var equimentVo = EquimentVoList(id = un.dealcode, list = equimentVoList)
                    problemReportVo.equimentVos.add(equimentVo)
                    Log.d(TAG, "selectProblem: ${problemReportVo.equimentVos}")
                }.onFailure {
                    Log.d(TAG, "selectProblem: ${it.message}")
                }
            }



            unresolvedVo.opQuaPics.forEach { op ->
                if (op.pictype == "1") {
                    op.picUrl?.let { it1 ->
                        problemReportVo.problemFiles.add(
                            FileVo(
                                url = it1,
                                path = "",
                                picId = op.id!!
                            )
                        )
                    }
                }
                if (op.pictype == "2") {
                    op.picUrl?.let { it1 ->
                        problemReportVo.dealFiles.add(
                            FileVo(
                                url = it1,
                                path = "",
                                picId = op.id!!
                            )
                        )
                    }
                }
            }

            problemDataList.add(
                problemReportVo
            )

            problemReportAdapter.notifyDataSetChanged()
        })
    }

    var gqywxxVo: GQYWXXVo? = null
    var unresolvedVo: UnresolvedVo? = null
    override fun initObserver() {
        gqStationViewModel.insertqueGQLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "上报成功", Toast.LENGTH_LONG).show()
                binding.btnSave.isEnabled = false
                binding.btnSave.setBackgroundResource(R.drawable.shape_dark)
                val orderId = intent.getStringExtra("orderId")
                Log.d(TAG, "insertqueGQLiveData:${orderId} ")
                if (orderId.isNotEmpty()) {
                    val products =
                        it.data?.problemList?.map {
                            Product(
                                productId = it.id,
                                productType = it.queType
                            )
                        }
                            ?.toMutableList()
                    val dealOrderDetailDto =
                        DealOrderDetailDto(orderDetailId = orderId, products = products)
                    gqStationViewModel.dealOrderDetail(dealOrderDetailDto)
                }


            } else {
                Toast.makeText(this, "上报失败 ${it.msg}", Toast.LENGTH_LONG).show()
            }

        }
        mainViewModel.gqywxxVoLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result && it.data.isNotEmpty()) {
                gqywxxVo = it.data
                binding.STCD.text = StringUtils.getNoNullData(it.data?.stcd)
                binding.STNM.text = StringUtils.getNoNullData(it.data?.stnm)
                binding.STTP.text =
                    StringUtils.getNoNullData("${it.data?.sttp}:${it.data?.sttpName}")
                mainViewModel.getQuaType(gqywxxVo!!.sttp)

            }

        }
        mainViewModel.quaTypeVoListLiveData.observe(this) {
            dataList.clear()
            if (it.result && it.data.isNotEmpty()) {
                dataList.addAll(it.data!!)
            }
            refreshQuaTypeView()
            val id = intent.getStringExtra("id")
            val queDeal = intent.getStringExtra("queDeal")
            Log.d(TAG, "initObserver: ${queDeal}")


            if (id != null) {
                if (queDeal == "已解决") {
                    gqStationViewModel.getResolved(
                        id = id,
                        stcd = gqywxxVo!!.stcd!!,
                        sttp = gqywxxVo!!.sttp!!
                    )
                } else {
                    gqStationViewModel.getUnresolved(
                        id = id,
                        stcd = gqywxxVo!!.stcd!!,
                        sttp = gqywxxVo!!.sttp!!
                    )
                }


            }


        }
        gqStationViewModel.unresolvedVoLiveData.observe(this) {
            Log.d(TAG, "unresolvedVoLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                unresolvedVo = it.data
                val d = dataList.find { d -> d.id == it.data?.queType }
                d?.selected = true
                refreshQuaTypeView()
                selectProblem(it.data!!.queType!!, it.data?.queTypeName, unresolvedVo = it.data!!)
                binding.resUsername.setText(it.data!!.resUsername)
                binding.resPhone.setText(it.data!!.resPhone)
                binding.createtime.setText(it.data!!.createtime)

                binding.quePhone.setText(it.data!!.quePhone)
                binding.queUsername.setText(it.data!!.queUsername)
                binding.queAfterTime.setText(it.data!!.queAfterTime)
            }

        }

    }


    override fun initListener() {
        binding.btnSave.setOnClickListener {
            lifecycleScope.launch {
                try {
                    if (problemDataList.isNullOrEmpty()) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请选择问题类型",
                            Toast.LENGTH_LONG
                        ).show();

                        return@launch
                    }
                    val emptyProblemDesc = problemDataList.find { it.problemDesc.isNullOrEmpty() }
                    if (emptyProblemDesc != null) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请填写问题内容",
                            Toast.LENGTH_LONG
                        ).show();

                        return@launch
                    }


                    val emptyProblemFiles =
                        problemDataList.find { it.problemFiles.isNullOrEmpty() || it.problemFiles.size <= 1 }
                    if (emptyProblemFiles != null) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请上传问题图片",
                            Toast.LENGTH_LONG
                        ).show();

                        return@launch
                    }

                    val emptyDealMethods =
                        problemDataList.find {
                            (it.dealMethods.isNullOrEmpty()
                                    || !it.dealMethods!!.find { it.selected }.isNotEmpty())
                                    && it.queDeal == "1"
                        }

                    if (emptyDealMethods != null) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请选择处理方式",
                            Toast.LENGTH_LONG
                        ).show();
                        return@launch
                    }
                    //是否包含更换设备
                    val exiEmptyEquimentVos = problemDataList.filter {
                        it.equimentVos.isNotEmpty() && it.queDeal == "1"
                    }
                    exiEmptyEquimentVos.forEach { v ->
                        v.equimentVos.forEach { d ->
                            if (d.list.isNotEmpty()) {
                                if (d.list?.get(1)?.equipment.isNullOrEmpty()) {
                                    Toast.makeText(
                                        this@GQStationReportDetailActivity,
                                        "请选择更换后设备",
                                        Toast.LENGTH_LONG
                                    ).show();
                                    return@launch
                                }
                            }
                        }
                    }

                    val emptyDealDesc =
                        problemDataList.find { it.dealDesc.isNullOrEmpty() && it.queDeal == "1" }
                    if (emptyDealDesc != null) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请填写处理描述",
                            Toast.LENGTH_LONG
                        ).show();

                        return@launch
                    }

                    val emptyDealFiles =
                        problemDataList.find { (it.dealFiles.isNullOrEmpty() || it.dealFiles.size <= 1) && it.queDeal == "1" }
                    if (emptyDealFiles != null) {
                        Toast.makeText(
                            this@GQStationReportDetailActivity,
                            "请上传处理图片",
                            Toast.LENGTH_LONG
                        ).show();
                        return@launch
                    }


                    ProgressDialog.show(this@GQStationReportDetailActivity)
                    Log.d(TAG, "initListener: $problemDataList")
                    val problemList = mutableListOf<ProblemDto>()
                    val problemUploadDto = ProblemUploadDto()
                    problemDataList.forEach { p ->
                        val problemDto = ProblemDto()
                        problemDto.queId = intent.getStringExtra("id")
                        problemDto.queType = p.id
                        problemDto.queContent = p.problemDesc
                        problemDto.resolved = getResolved(p.queDeal)
                        problemDto.needAssist = getNeedAssist(p.needAssist)
                        val problemPicIds = mutableListOf<String>()
                        //上传上报图片
                        for (i in 0 until p.problemFiles.size) {
                            val problemFile = p.problemFiles[i]
                            if (problemFile.isNotEmpty()) {
                                val dto = SaveQuePicDto(
                                    stcd = gqywxxVo!!.stcd,
                                    DictId = p.id,
                                    sttp = gqywxxVo!!.sttp,
                                    stnm = gqywxxVo!!.stnm,
                                    lttdandlgtd = "00,00",
                                    PicType = "1"
                                )
                                if (problemFile.picId.isNotEmpty()) {
                                    problemPicIds.add(problemFile.picId)
                                } else if (problemFile.path.isNotEmpty()) {
                                    val uploadFileDtoList = mutableListOf<UploadFileDto>()
                                    uploadFileDtoList.add(
                                        UploadFileDto(
                                            file = File(problemFile.path),
                                            fileName = "${p.id}_1_${i}"
                                        )
                                    )
                                    val res = gqStationViewModel.saveQuePic(
                                        dto = dto,
                                        uploadFileDtoList = uploadFileDtoList
                                    )
                                    if (res.success == true && res.data.isNotEmpty()) {
                                        problemPicIds.add(res.data!!)
                                    }
                                }

                            }
                        }
                        problemDto.problemPicIds = problemPicIds


                        if (p.queDeal == "1") {
                            //解决描述
                            problemDto.processIng = p.dealDesc
                            //处理方式
                            val clIds = p.dealMethods?.filter { it.selected }?.map { it.id }
                                ?.toMutableList()
                            if (clIds != null) {
                                problemDto.clId = clIds
                            }

                            //解决问题
                            val resolvedPicIds = mutableListOf<String>()
                            //上传解决图片
                            for (i in 0 until p.dealFiles.size) {
                                val dealFile = p.dealFiles[i]
                                if (dealFile.isNotEmpty()) {
                                    val dto = SaveQuePicDto(
                                        stcd = gqywxxVo!!.stcd,
                                        DictId = p.id,
                                        sttp = gqywxxVo!!.sttp,
                                        stnm = gqywxxVo!!.stnm,
                                        lttdandlgtd = "00,00",
                                        PicType = "2"
                                    )
                                    if (dealFile.picId.isNotEmpty()) {
                                        resolvedPicIds.add(dealFile.picId)
                                    } else if (dealFile.path.isNotEmpty()) {
                                        val uploadFileDtoList = mutableListOf<UploadFileDto>()
                                        uploadFileDtoList.add(
                                            UploadFileDto(
                                                file = File(dealFile.path),
                                                fileName = "${p.id}_2_${i}"
                                            )
                                        )
                                        val res = gqStationViewModel.saveQuePic(
                                            dto = dto,
                                            uploadFileDtoList = uploadFileDtoList
                                        )
                                        if (res.success == true && res.data.isNotEmpty()) {
                                            resolvedPicIds.add(res.data!!)
                                        }
                                    }

                                }

                            }
                            problemDto.resolvedPicIds = resolvedPicIds
                        }
                        p.equimentVos.forEach { e ->
                            e.list?.forEach { l ->
                                val equipment = l.equipment
                                if (equipment != null && equipment.contains("_")) {
                                    problemDto.relevanceListMap.add(
                                        EquimentKeyValueVo(
                                            key = l.cl_CODE,
                                            value = equipment.split("_")[1]
                                        )
                                    )
                                } else {
                                    problemDto.relevanceListMap.add(
                                        EquimentKeyValueVo(
                                            key = l.cl_CODE,
                                            value = equipment
                                        )
                                    )
                                }


                            }


                        }


                        problemList.add(problemDto)


                    }
                    val loginVo = MMKV.defaultMMKV()
                        .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)
//                    problemUploadDto.sttp = gqywxxVo!!.sttp
                    problemUploadDto.stnm = gqywxxVo!!.stnm
                    problemUploadDto.stcd = gqywxxVo!!.stcd
                    //问题上报人信息
                    problemUploadDto.queUsername =
                        if (unresolvedVo?.queUsername.isNullOrEmpty()) loginVo?.userName else unresolvedVo?.queUsername
                    problemUploadDto.queUserid =
                        if (unresolvedVo?.queUserid.isNullOrEmpty()) loginVo?.id else unresolvedVo?.queUserid
                    problemUploadDto.quePhone =
                        if (unresolvedVo?.quePhone.isNullOrEmpty()) loginVo?.userName else unresolvedVo?.quePhone

                    //处理人信息
                    problemUploadDto.resUsername = loginVo?.userName
                    problemUploadDto.resUserid = loginVo?.id
                    problemUploadDto.resPhone = loginVo?.userMobile

                    problemUploadDto.problemList = problemList

                    Log.d(TAG, "initListener: problemUploadDto ${problemUploadDto}")
                    gqStationViewModel.insertqueGQ(problemUploadDto)
                } catch (e: Exception) {
                    ProgressDialog.hide()
                    Toast.makeText(
                        this@GQStationReportDetailActivity,
                        "上报异常 ${e.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }


            }

        }

    }

    private fun getNeedAssist(needAssist: String?): String {
        return if (needAssist == "1") {
            "1"
        } else {
            "0"
        }


    }

    private fun getResolved(reportOrDeal: String?): String {
        return if (reportOrDeal == "1") {
            "1"
        } else {
            "0"
        }

    }


    override fun initData() {
        ProgressDialog.show(this)
        getGQStationInfo()
    }

    private fun getGQStationInfo() {
        val stcd = intent.getStringExtra("stcd")
        mainViewModel.getGQYWXX(STCD = stcd!!)

    }


    override fun initView() {
        setTitle(
            title = R.string.str_operation_record,
            isBack = true,

            )
        binding.rvList.layoutManager = FlexboxLayoutManager(this)
        binding.rvList.adapter = adapter


        binding.rvProblem.layoutManager = LinearLayoutManager(this)
        val map = hashMapOf(RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(this, 20f))
        binding.rvProblem.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvProblem.adapter = problemReportAdapter
        val queDeal = intent.getStringExtra("queDeal")

        if (queDeal == "已解决") {
            binding.btnSave.isEnabled = false
            binding.btnSave.setBackgroundResource(R.drawable.shape_dark)
            binding.llQue.visibility = View.VISIBLE
            binding.llRes.visibility = View.VISIBLE
        } else {
            binding.btnSave.isEnabled = true
            binding.btnSave.setBackgroundResource(R.drawable.shape_btn)
            binding.llQue.visibility = View.VISIBLE
            binding.llRes.visibility = View.GONE
        }

    }


    override fun setContentView() {
        binding = ActivityGqstationReportBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }


    fun equipment(id: String, resp: ((CommonBean<List<EquimentVo>>) -> Unit)? = null) {
        gqStationViewModel.equipment(
            sttp = gqywxxVo!!.sttp!!,
            stcd = gqywxxVo!!.stcd!!,
            id = id,
            resp = resp
        )

    }


    fun showSelectModel(model: String, okAction: (String?, String?) -> Unit) {
        Log.d(TAG, "showSelectModel: showSelectModel ${model}")
        ProgressDialog.show(this)
        gqStationViewModel.getDictName(model) {
            ProgressDialog.hide()
            Log.d(TAG, "getDictName: getDictName ${it.data}")
            if (it.data.isNotEmpty()) {
                showSelectWheelViewDialog(okAction = { index ->
                    Log.d(TAG, "selected: ${it.data?.get(index)}")
                    val dataCode = it.data?.get(index)!!.dataCode
                    val dataName = it.data?.get(index)!!.dataName
                    okAction.invoke(dataCode, dataName)


                }, dictVoList = it.data!!)
            }

        }
    }


}